package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.model.bo.goods.GoodsDetailsBo;
import com.cskaoyan.mall.model.bo.goods.UpdateGoodSpec;
import com.cskaoyan.mall.model.bo.goods.UpdateGoodsDetailsBo;
import com.cskaoyan.mall.model.bo.message.MessageBo;
import com.cskaoyan.mall.model.po.Goods;
import com.cskaoyan.mall.model.po.Spec;
import com.cskaoyan.mall.model.po.Type;
import com.cskaoyan.mall.model.bo.goods.GoodsTypeBo;
import com.cskaoyan.mall.model.vo.goods.*;
import com.cskaoyan.mall.model.vo.message.CustomerVo;
import com.cskaoyan.mall.model.vo.message.GoodsLeaveMessageVo;
import com.cskaoyan.mall.model.vo.message.LeaveMessageVo;
import com.cskaoyan.mall.service.lmpl.GoodsServiceImpl;
import com.cskaoyan.mall.service.lmpl.MessageServiceImpl;
import com.cskaoyan.mall.utils.FileUploadUtils;
import com.cskaoyan.mall.utils.GoodsResult;
import com.google.gson.Gson;
import com.sun.scenario.effect.SepiaTone;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: GoodsServlet
 * @Description: TODO
 * @Auther 庄左
 * @Date 2022/6/30 10:33
 * @Version
 **/
@WebServlet("/api/admin/goods/*")
public class GoodsServlet extends HttpServlet {
    private MessageServiceImpl messageService = new MessageServiceImpl();
    private GoodsServiceImpl goodsService = new GoodsServiceImpl();
    private Gson gson = new Gson();
    private GoodsResult result = new GoodsResult();

    //====================================================================================//
    //获取json字符串
    private String getJsonString(HttpServletRequest req) throws IOException {
        ServletInputStream inputStream = req.getInputStream();
        //写入字节数组的输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        //转为字符串
        return outputStream.toString("utf-8");
    }
    //=====================================================================================//

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/admin/goods/", "");
        if ("getType".equals(replace)) {
            getType(req, resp);
        }
        if ("getGoodsByType".equals(replace)) {
            getGoodsByType(req, resp);
        }
        if ("getGoodsInfo".equals(replace)) {
            getGoodsInfo(req, resp);
        }
        if ("deleteGoods".equals(replace)) {
            deleteGoods(req, resp);
        }
        if ("deleteType".equals(replace)) {
            deleteType(req, resp);
        }
        if ("noReplyMsg".equals(replace)) {
            noReplyMsg(req, resp);
        }
        if ("repliedMsg".equals(replace)) {
            repliedMsg(req, resp);
        }
    }

    /**
     * @Author: 庄左
     * @Description: 已经回复的留言信息
     * @DateTime: 2022/7/2 21:18
     */
    private void repliedMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<LeaveMessageVo> leaveMessages = messageService.selectReplyMessageDetails();
        //因为已回复和未回复的信息在同一张表中，所以需要进行筛选，筛选结果使用另一个列表集合来容纳
        List<LeaveMessageVo> messageVos = new ArrayList<>();
        for (LeaveMessageVo message : leaveMessages) {
            //遍历该集合，如果回复信息栏为空，说明该信息未回复，跳过
            if (message.getReplyContent() == null) {
                continue;
            }
            Integer id = message.getId();
            // 获取id去表中查找对应的商品以及提问者的名字
            GoodsLeaveMessageVo goodsName = messageService.selectGoodsName(id);
            CustomerVo userName = messageService.selectUserName(id);
            message.setGoods(goodsName);
            message.setUser(userName);
            messageVos.add(message);
        }
        result.setCode(0);
        result.setData(messageVos);
        resp.getWriter().println(gson.toJson(result));

    }

    /**
     * @Author: 庄左
     * @Description: 未回复的留言信息
     * @DateTime: 2022/7/2 21:33
     */
    private void noReplyMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<LeaveMessageVo> leaveMessages = messageService.selectMessageDetails();
        List<LeaveMessageVo> messageVos = new ArrayList<>();
        for (LeaveMessageVo message : leaveMessages) {
            if (message.getReplyContent() != null) {
                continue;
            }
            Integer id = message.getId();
            GoodsLeaveMessageVo goodsName = messageService.selectGoodsName(id);
            CustomerVo userName = messageService.selectUserName(id);
            message.setGoods(goodsName);
            message.setUser(userName);
            messageVos.add(message);
        }
        result.setCode(0);
        result.setData(messageVos);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 通过类的id, 删除该类别
     * TODO:需要该类下无商品才可删除
     * @DateTime: 2022/7/2 21:33
     */
    private void deleteType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("typeId"));
        goodsService.deleteType(id);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 通过商品的id 删除该商品
     * @DateTime: 2022/7/2 21:35
     */
    private void deleteGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        Integer id = Integer.valueOf(req.getParameter("id"));
        goodsService.deteleGoods(id);

        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));

    }

    /**
     * @Author: 庄左
     * @Description: 商品的编辑,
     * TODO 规格的回显bug----已解决
     * @DateTime: 2022/7/2 21:37
     */
    private void getGoodsInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取请求参数
        Integer id = Integer.valueOf(req.getParameter("id"));
        //用来封装商品信息和规格列表的类
        EditorGoodsMessage ogm = new EditorGoodsMessage();

        GoodVo goodVo = goodsService.selectGood(id);
        List<SpecVo> specVos = goodsService.selectSpec(id);

        ogm.setGoods(goodVo);
        ogm.setSpecs(specVos);
        result.setCode(0);
        result.setData(ogm);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 通过类别id查找所有商品
     * @DateTime: 2022/7/1 15:33
     */
    private void getGoodsByType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer typeId = Integer.valueOf(req.getParameter("typeId"));
        List<GoodsMessageVo> goods = goodsService.selectGoodsByType(new Type(typeId, null));
        result.setCode(0);
        result.setData(goods);
        resp.getWriter().println(gson.toJson(result));

    }

    //查找所有类别
    private void getType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<GoodsTypeVo> goodsTypeVo = goodsService.selectType();
        result.setCode(0);
        result.setData(goodsTypeVo);
        resp.getWriter().println(gson.toJson(result));

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String replace = requestURI.replace(req.getContextPath() + "/api/admin/goods/", "");
        if ("addType".equals(replace)) {
            addType(req, resp);
        }
        if ("addGoods".equals(replace)) {
            addGoods(req, resp);
        }
        if ("imgUpload".equals(replace)) {
            imgUpload(req, resp);
        }
        if ("updateGoods".equals(replace)) {
            updateGoods(req, resp);
        }
        if ("addSpec".equals(replace)) {
            addSpec(req, resp);
        }
        if ("reply".equals(replace)) {
            reply(req, resp);
        }
        if ("deleteSpec".equals(replace)){
            deleteSpec(req,resp);
        }

    }



    /**
     * @Author: 庄左
     * @Description: 回复留言, 回复时将根据该留言的id查找到该条记录, 然后将回复栏更新
     * @DateTime: 2022/7/2 21:49
     */
    private void reply(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        MessageBo messageBo = gson.fromJson(getJsonString(req), MessageBo.class);
        messageService.updateReplyContent(messageBo);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 增加商品的规格, 根据????
     * TODO:实现增加规格功能???,可以通过商品编辑中保存修改来添加,但由于该项目前端接口并未如此实现
     * @DateTime: 2022/7/2 21:50
     */
    private void addSpec(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UpdateGoodSpec updateGoodSpec = gson.fromJson(getJsonString(req), UpdateGoodSpec.class);
        result.setCode(0);
        result.setData(new Spec(null, updateGoodSpec.getId(), updateGoodSpec.getSpecName(), updateGoodSpec.getUnitPrice(), updateGoodSpec.getStockNum()));
        resp.getWriter().println(gson.toJson(result));
    }

    /**
     * @Author: 庄左
     * @Description: 增加商品
     * @DateTime: 2022/7/2 21:56
     */
    private void addGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        GoodsDetailsBo goodsDetailsBo = gson.fromJson(getJsonString(req), GoodsDetailsBo.class);
        goodsService.addGoods(goodsDetailsBo);
        //通过商品
        List<GoodsMessageVo> goods = goodsService.selectGoodsByType(new Type(Integer.valueOf(goodsDetailsBo.getTypeId()), null));
        Integer id = null;
        for (GoodsMessageVo good : goods) {
            id = good.getId();
        }
        goodsService.insertSpec(goodsDetailsBo, id);
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));

    }


    /**
     * @Author: 庄左
     * @Description: TODO 图片的回显bug----已解决
     * @DateTime: 2022/7/1 15:34
     */
    private void imgUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        boolean multipartContent = ServletFileUpload.isMultipartContent(req);
        if (!multipartContent) {
            return;
        }
        Goods goods = new Goods();
        Map<String, String> map = FileUploadUtils.getFileUploadOfMap(req);
        try {
            BeanUtils.populate(goods, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        result.setCode(0);
        String path = map.get("file");

        result.setData(path);
        resp.getWriter().println(gson.toJson(result));
    }

    private void updateGoods(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        UpdateGoodsDetailsBo updateGoodsDetailsBo = gson.fromJson(getJsonString(req), UpdateGoodsDetailsBo.class);
        // 更新商品
        goodsService.selectUpdateGood(updateGoodsDetailsBo);
        //更新商品的规格
        goodsService.selectUpdateGoodSpec(updateGoodsDetailsBo, updateGoodsDetailsBo.getId());
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }

    //单独删除规格
    private void deleteSpec(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Spec spec = gson.fromJson(getJsonString(req), Spec.class);

        Integer goodId = spec.getGoodId();
        String name = spec.getName();
        goodsService.deleteSpec(goodId,name);

        result.setCode(0);

        resp.getWriter().println(gson.toJson(result));

    }

    private void addType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        GoodsTypeBo goodsTypeBo = gson.fromJson(getJsonString(req), GoodsTypeBo.class);
        boolean flag = goodsService.addType(goodsTypeBo);
        if (!flag) {
            result.setCode(10000);
            result.setMessage("该种类已存在");
            resp.getWriter().println(gson.toJson(result));
            return;
        }
        result.setCode(0);
        resp.getWriter().println(gson.toJson(result));
    }
}
